// public/js/card-game.js

// 从 URL 获取房间ID
const urlParams = new URLSearchParams(window.location.search);
const currentRoomId = urlParams.get('roomId');

if (!currentRoomId) {
    alert('无效的房间ID！将返回大厅。');
    window.location.href = '/';
}

const socket = io('http://localhost:3001');

// DOM 元素
const currentRoomIdSpan = document.getElementById('current-room-id');
const messageArea = document.getElementById('message-area');
const gameCanvas = document.getElementById('game-canvas');
const leaveGameBtn = document.getElementById('leave-game-btn');

currentRoomIdSpan.textContent = currentRoomId;

// 事件监听
leaveGameBtn.addEventListener('click', () => {
    socket.emit('leave_room', { roomId: currentRoomId });
});

// Socket.IO 事件
socket.on('connect', () => {
    console.log('连接到卡牌游戏服务器');
    // 重新连接后，需要让服务器知道你回到了游戏房间
    // 一个简单的方式是再次发送 join_room 事件
    const playerName = localStorage.getItem('playerName') || prompt('请输入你的昵称:');
    if (playerName) {
        localStorage.setItem('playerName', playerName); // 存储昵称
        socket.emit('join_room', { roomId: currentRoomId, playerName: playerName });
    }
});

socket.on('game_started', (data) => {
    if (data.game === 'card_game') {
        updateMessage('游戏开始！');
        initGameUI(data.state);
    }
});

socket.on('opponent_action', (data) => {
    if (data.action === 'play_card') {
        updateMessage(`对手出了一张牌: ${data.data.card}`);
    }
});

socket.on('room_left_success', () => {
    window.location.href = '/';
});

// 辅助函数
function initGameUI(state) {
    // 假设 state.playerHands 包含当前玩家的手牌
    const myPlayerId = socket.id;
    const myHand = state.playerHands[myPlayerId] || [];

    gameCanvas.innerHTML = `
        <h3>你的手牌</h3>
        <div id="my-hand">
            ${myHand.map(card => `<div class="card" data-card="${card}">${card}</div>`).join('')}
        </div>
    `;

    // 为每张牌添加点击事件
    document.querySelectorAll('.card').forEach(cardElement => {
        cardElement.addEventListener('click', () => {
            const card = cardElement.dataset.card;
            socket.emit('game_action', {
                roomId: currentRoomId,
                action: 'play_card',
                actionData: { card: card }
            });
            // 简单处理：移除已出的牌
            cardElement.remove();
        });
    });
}

function updateMessage(text, color = 'inherit') {
    messageArea.textContent = text;
    messageArea.style.color = color;
}